package com.adv.netWork01.weatherServer;

import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.net.*;

public class WeatherServerThread extends Thread {
	private ServerSocket s;

	private WeatherServerThread(ServerSocket s) {
		this.s = s;
		super.setName(String.valueOf(s.getInetAddress()));

	}

	@Override
	public void run() {
		System.out.println("-----------天气服务器-------------");
		while (true) {
			try {
				Socket client = s.accept();
				System.out.println("客户端的信息:" + client.getInetAddress() + ",端口:" + client.getPort() + "已连接服务器");
				InputStream is = client.getInputStream();
				OutputStream os = client.getOutputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				PrintWriter pw = new PrintWriter(os);
				pw.println("<-天气服务器->" + "请输入：<气温，风力，pm2.5,湿度>，可查询相相关数据");
				pw.flush();
				String line = "";
				while (true) {
					line = br.readLine();
					String str = "";
					System.out.println("客户端<" + client.getInetAddress() + ">说：" + line);
					if (line.equalsIgnoreCase("气温")) {
						str = "气温22°C";
					} else if (line.equalsIgnoreCase("风力")) {
						str = "风力3-4级";
					} else if (line.equalsIgnoreCase("pm2.5")) {
						str = "pm2.5为80/m³";
					} else if (line.equalsIgnoreCase("湿度")) {
						str = "湿度15%";
					} else if (line.equalsIgnoreCase("quit")) {
						break;
					} else {
						str = "暂未开通此服务！";
					}
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					pw.println(sf.format(new Date()) + "=>>" + str);
					pw.flush();
				}
				if (line.equalsIgnoreCase("quit")) {
					System.out.println("退出系统！");
					break;
				}

			} catch (Exception e) {
				System.err.println("服务器故障，关闭服务器");
				e.printStackTrace();
			} finally {
				try {
					if (s != null)
						s.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		WeatherServerThread wst = new WeatherServerThread(new ServerSocket(9999));
		wst.start();

	}

}
